<?php

namespace app\admin\model;


/**
 * Author:Jack Wang
 * Time:2018-10-22 10:13:36
 * Describe:配置模型
 * Class Config
 * @package app\admin\model
 */
class Config extends Base
{

    //添加图纸配置参数
    public function drawingApiConfigAdd($config_type,$data){
        $data = collection($data)->toArray();//data变成数组方便调试
        foreach ($data as $key=>$val){//遍历data数组集合
            $config_id = $this->getConfigId($val["config_name"]);
            if(!empty($config_id)){
                unset($data[$key]);//删除重复配置
            }else{
                $data[$key]['config_type'] = $config_type;
            }
        }
        return $this->mySaveAll($data);
    }

    //获取配置类型列表
    public function getConfigTypeList($config_type){
        return $this->field("config_id,config_name")->where("config_type",$config_type)->select();
    }

    //根据条件获取配置id
    public function getConfigId($config_name){
        return $this->where("config_name",$config_name)->value("config_id");
    }

    //根据ID获取name
    public function getConfigName($config_id){
        return $this->where("config_id",$config_id)->value("config_name");
    }

    //根据条件获取配置id
    public function getTypeBuildSql($count_fields = "num"){
        return $this->field([
                "config_type",
                "count(config_id) ".$count_fields
            ])->group("config_type")->buildSql();
    }

    //获取type下的配置数量
    public function getTypeNumber($config_type){
        return $this->where("config_type",$config_type)->count();
    }

    //配置列表
    public function configList($config_type,$keyword = ""){
        return $this
            ->field([
                "config_id",
                "config_name",
            ])
            ->where("config_type",$config_type)
            ->where(function ($q)use ($keyword){
                if(!empty($keyword)){
                    $q->whereOr("config_name","like","%".$keyword."%");
                }
            })
            ->page($this->after_page)
            ->limit($this->after_limit)
            ->select();
    }

    //配置列表总数
    public function configListCount($config_type,$keyword = ""){
        return $this
            ->where("config_type",$config_type)
            ->where(function ($q)use ($keyword){
                if(!empty($keyword)){
                    $q->whereOr("config_name","like","%".$keyword."%");
                }
            })
            ->count();
    }


    //返回键值对配置
    public function getConfigTypeListArray($config_type){
        $result = [];
        $select = $this->field("config_id,config_name")->where("config_type",$config_type)->select();
        foreach ($select as $val){
            $result[$val["config_id"]] = $val["config_name"];
        }
        return $result;
    }
}